package cn.apotato.security.service;

import cn.apotato.common.core.constant.CacheConstants;
import cn.apotato.common.core.constant.SecurityConstants;
import cn.apotato.common.core.utils.IpUtils;
import cn.apotato.common.core.utils.JwtUtils;
import cn.apotato.common.core.utils.ServletUtils;
import cn.apotato.common.core.utils.StringUtils;
import cn.apotato.common.core.utils.uuid.IdUtils;
import cn.apotato.common.model.LoginUser;
import cn.apotato.common.model.system.SysUser;
import cn.apotato.modules.redis.service.RedisService;
import cn.apotato.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 令牌服务
 *
 * @author 胡晓鹏
 * @date 2023/05/30
 */
@Component
public class TokenService {

    @Autowired
    private RedisService redisService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;


    /**
     * 创建令牌
     *
     * @param loginUser 登录用户
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        SysUser sysUser = loginUser.getSysUser();
        if (sysUser != null) {
            Long userId = sysUser.getId();
            // 账号
            String account = sysUser.getAccount();
            // 用户名
            String username = sysUser.getUsername();
            // 组织id
            String orgId = sysUser.getOrgId();

            // 设置用户信息
            loginUser.setToken(token);
            loginUser.setUserid(userId);
            loginUser.setOrgId(orgId);
            loginUser.setUsername(username);
            loginUser.setAccount(account);
            loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
            // 缓存并刷新用户信息
            refreshToken(loginUser);

            // Jwt信息
            Map<String, Object> claimsMap = new HashMap<>(3);
            claimsMap.put(SecurityConstants.USER_KEY, token);
            claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
            claimsMap.put(SecurityConstants.DETAILS_USERNAME, username);

            Map<String, Object> rspMap = new HashMap<>(3);
            rspMap.put("access_token", JwtUtils.createToken(claimsMap));
            rspMap.put("expires_in", expireTime);

            return rspMap;
        }
        return null;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userKey = JwtUtils.getUserKey(token);
                return redisService.getValue(getTokenKey(userKey));
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = JwtUtils.getUserKey(token);
            redisService.delete(getTokenKey(userKey));
        }
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌
     *
     * @param loginUser 登录用户
     */
    private void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setValue(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 获得令牌密钥
     *
     * @param token 令牌
     * @return {@link String}
     */
    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}
